# -*- coding: utf-8 -*-
import cgi
import datetime
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp

import views.MP as MPv
import models.milestonePlan as MPm
import models.MPTemplates as MPTm
import models.user as um
import decorator as dc

from models.enhancedModel import EnhancedModel

class MPTemplateContr( webapp.RequestHandler ): 
    @dc.decorate
    def get(self, action, *params, **kwds):
        if not um.UserModel.currentHasPermission("MPTUploadForm"):
          self.response.out.write("<font color=\"red\"><b>You have no rights to do this action.</b></font>")
          return
        ret = ''' <h2>Milestone plan templates</h2>
           <b>Upload new</b><br/>
             <form action="/mp/upload" method="post" enctype="multipart/form-data">
             <div><input type="file" id="fileUpload" name="upload" /></div>
             <div><input type="submit" value="Upload" /></div>
		   <br/>
           <b>Current templates:</b><br/>
             <pre>%s</pre> ''' % (MPTm.MPTemplateModel.file())

        self.response.out.write(ret)

    def post(self, action, *params, **kwds):
        if not um.UserModel.currentHasPermission("MPTUploadForm"):
          self.response.out.write("<font color=\"red\"><b>You have no rights to do this action.</b></font>")
          return
          
        newTemplates = self.request.get('upload')
        record = EnhancedModel.queryLatest( MPTm.MPTemplateModel, 1 ).filter('archival =', False).get()
        if record == None:
          record = MPTm.MPTemplateModel( ident = 1)
        record.data = newTemplates
        record.put()
        self.redirect('/mp/upload?done=True')